using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RiceShop.Models;
using RiceShop.Services;
using RiceShop.Extensions;

namespace RiceShop.Controllers
{
    /// <summary>
    /// 收货地址管理控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AddressController : ControllerBase
    {
        private readonly IAddressService _addressService;

        /// <summary>
        /// 构造函数，注入地址服务
        /// </summary>
        /// <param name="addressService">地址服务接口</param>
        public AddressController(IAddressService addressService)
        {
            _addressService = addressService;
        }

        /// <summary>
        /// 获取当前用户的收货地址列表
        /// </summary>
        /// <returns>地址列表，包含每个地址的详细信息</returns>
        [HttpGet]
        public async Task<ActionResult> GetAddresses()
        {
            try
            {
                var userId = User.GetUserId();
                var addresses = await _addressService.GetAddressListAsync(userId);

                // 转换为前端需要的数据结构
                var addressList = addresses.Select(address => new
                {
                    id = address.Id,
                    receiverName = address.ReceiverName,
                    phoneNumber = address.PhoneNumber,
                    province = address.Province,
                    city = address.City,
                    district = address.District,
                    detailAddress = address.DetailAddress,
                    isDefault = address.IsDefault
                }).ToList();

                return Ok(ApiResponse<object>.Ok(addressList, "获取地址列表成功"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"获取地址列表失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 新建收货地址
        /// </summary>
        /// <param name="address">地址信息对象</param>
        /// <returns>新创建的地址信息</returns>
        [HttpPost]
        public async Task<ActionResult> CreateAddress([FromBody] Address address)
        {
            try
            {
                var userId = User.GetUserId();
                var createdAddress = await _addressService.CreateAddressAsync(userId, address);

                var addressData = new
                {
                    id = createdAddress.Id,
                    receiverName = createdAddress.ReceiverName,
                    phoneNumber = createdAddress.PhoneNumber,
                    province = createdAddress.Province,
                    city = createdAddress.City,
                    district = createdAddress.District,
                    detailAddress = createdAddress.DetailAddress,
                    isDefault = createdAddress.IsDefault
                };

                return Ok(ApiResponse<object>.Ok(addressData, "创建地址成功"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"创建地址失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 更新指定ID的收货地址信息
        /// </summary>
        /// <param name="id">地址ID</param>
        /// <param name="address">更新的地址信息</param>
        /// <returns>更新后的地址信息</returns>
        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateAddress(long id, [FromBody] Address address)
        {
            try
            {
                var userId = User.GetUserId();
                var updatedAddress = await _addressService.UpdateAddressAsync(userId, id, address);

                var addressData = new
                {
                    id = updatedAddress.Id,
                    receiverName = updatedAddress.ReceiverName,
                    phoneNumber = updatedAddress.PhoneNumber,
                    province = updatedAddress.Province,
                    city = updatedAddress.City,
                    district = updatedAddress.District,
                    detailAddress = updatedAddress.DetailAddress,
                    isDefault = updatedAddress.IsDefault
                };

                return Ok(ApiResponse<object>.Ok(addressData, "更新地址成功"));
            }
            catch (KeyNotFoundException)
            {
                return NotFound(ApiResponse<object>.Error("地址不存在"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"更新地址失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 删除指定ID的收货地址
        /// </summary>
        /// <param name="id">要删除的地址ID</param>
        /// <returns>删除操作的结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteAddress(long id)
        {
            try
            {
                var userId = User.GetUserId();
                await _addressService.DeleteAddressAsync(userId, id);
                return Ok(ApiResponse<object>.Ok(null, "删除地址成功"));
            }
            catch (KeyNotFoundException)
            {
                return NotFound(ApiResponse<object>.Error("地址不存在"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"删除地址失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 设置指定地址为默认收货地址
        /// </summary>
        /// <param name="id">要设置为默认的地址ID</param>
        /// <returns>更新后的地址信息</returns>
        [HttpPut("{id}/default")]
        public async Task<ActionResult> SetDefaultAddress(long id)
        {
            try
            {
                var userId = User.GetUserId();
                var address = await _addressService.SetDefaultAddressAsync(userId, id);

                var addressData = new
                {
                    id = address.Id,
                    receiverName = address.ReceiverName,
                    phoneNumber = address.PhoneNumber,
                    province = address.Province,
                    city = address.City,
                    district = address.District,
                    detailAddress = address.DetailAddress,
                    isDefault = address.IsDefault
                };

                return Ok(ApiResponse<object>.Ok(addressData, "设置默认地址成功"));
            }
            catch (KeyNotFoundException)
            {
                return NotFound(ApiResponse<object>.Error("地址不存在"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"设置默认地址失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 获取默认收货地址
        /// </summary>
        /// <returns>默认地址信息</returns>
        [HttpGet("default")]
        public async Task<ActionResult> GetDefaultAddress()
        {
            try
            {
                var userId = User.GetUserId();
                var address = await _addressService.GetDefaultAddressAsync(userId);

                if (address == null)
                    return NotFound(ApiResponse<object>.Error("未找到收货地址"));

                var addressData = new
                {
                    id = address.Id,
                    receiverName = address.ReceiverName,
                    phoneNumber = address.PhoneNumber,
                    province = address.Province,
                    city = address.City,
                    district = address.District,
                    detailAddress = address.DetailAddress,
                    isDefault = address.IsDefault
                };

                return Ok(ApiResponse<object>.Ok(addressData, "获取默认地址成功"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<object>.Error($"获取默认地址失败: {ex.Message}"));
            }
        }
    }
}